// 工程化 
import Vue from 'vue'
import VueRouter from 'vue-router'
// 明确安装路由功能
Vue.use(VueRouter)

// 创建路由模块和配置路由
const router = new VueRouter({
    // 使用routes进行路由配置
    routes: [{
        name: 'deafault',
        path: '/',
        redirect: { name: 'index' }
    }, {
        name: 'login',
        path: '/login',
        component: () =>
            import ('@/views/user/login.vue')
    }, {
        name: 'register',
        path: '/register',
        component: () =>
            import ('@/views/user/register.vue')
    }, {
        name: 'personal',
        // 因为在个人中心需要获取用户详情，需要用id值进行发送请求，所以在路由中进行参数id的传值，在登录页面中跳转的时候，需要加上id参数
        path: '/personal/:id',
        component: () =>
            import ('@/views/user/personal.vue')
    }, {
        name: 'edit_profile',
        path: '/edit_profile/:id',
        component: () =>
            import ('@/views/user/edit_profile.vue')
    }, {
        name: 'index',
        path: '/index',
        component: () =>
            import ('@/views/index.vue')
    }, {
        name: 'articleDetail',
        path: '/articleDetail/:id',
        component: () =>
            import ('@/views/article/articleDetail.vue')
    }, {
        name: 'myfollow',
        path: '/myfollow',
        component: () =>
            import ('@/views/user/myfollow.vue')
    }, {
        name: 'mystar',
        path: '/mystar',
        component: () =>
            import ('@/views/user/mystar.vue')
    }, {
        name: 'comment',
        path: '/comment/:id',
        component: () =>
            import ('@/views/article/comment.vue')
    }, {
        name: 'cateManager',
        path: '/cateManager',
        component: () =>
            import ('@/views/cateManager.vue')
    }]
})

// toast虽然在全局中引入了，但是只有组件才能使用，js文件用不到，所以需要在这里重新引入一次，使用Toast
import { Toast } from 'vant';
router.beforeEach((to, from, next) => {
    let arr = ['personal', 'edit_profile', 'cateManager']
    console.log('to----------', to);
    console.log('from----------', from);
    // 如果路由包含了/personal/，就进入这个判断，其他的就继续下一步next()
    if (arr.indexOf(to.name) != -1) {
        // 获取到之前存储的token值，再根据token值进行判断操作
        let token = localStorage.getItem('mytoken')

        // 有token值操作：直接next()，下一步
        if (token) {
            next()
        } else {
            // 提示
            Toast('还没登录，请登录')

            // 没有token值，就是没有登录，所以路由重定向到登录页面
            next({ name: 'login' })
        }
    } else {
        next()
    }
})

// 暴露
export default router